import { useState, useContext, useEffect, useRef } from 'react'
import { useNavigate } from 'react-router-dom'
import { Unstable_Grid2 as Grid, Menu, MenuItem,Avatar, Box, Tabs, Tab, FormControlLabel, Stack,  Button, Container, Typography  } from '@mui/material';
import { OndemandVideo, Tv, PhoneAndroid, MusicNote, PlayCircle, Photo } from '@mui/icons-material';
import * as iconsObj from '@mui/icons-material';
import { connect } from 'react-redux'
import { updateUserInfo,changIdx, selectCounter } from '../store/models/counterSlice'
import { useSnackbar } from "notistack";
import { ColorTheme } from '../App';
import request from "../../api/index"
import { TransitionGroup, CSSTransition } from 'react-transition-group'

import MaterialUISwitch from '../component/MUISwitch';
import CustomTabPanel from '../component/CustomTabPanel';
import { LoginView, RegisterView, Profile } from './home/LoginRister'
import Card from './home/Card';
import Loading from '../component/Loading';



function a11yProps(index) {
  return {
    id: `simple-tab-${index}`,
    'aria-controls': `simple-tabpanel-${index}`,
  };
}


const mapStateToProps = (state) => {
  const counter = selectCounter(state)
  return {
    ...counter
  }
}

const mapDispatchToProps = (dispatch) => {
  return {
    updateUserInfo: (arg) => dispatch(updateUserInfo(arg)),
    change: (arg) => dispatch(changIdx(arg))
  }
}



function Home(props){
  
  const tabIdx = props.tabIdx

  const { changeTheme, theme } = useContext(ColorTheme)
  const [list,setlist] = useState([])
  const [loginOpen,setloginOpen] = useState(false)
  const [regOpen,setregOpen] = useState(false)
  const [proOpen,setproOpen] = useState(false)

  const [tabList,settabList] = useState([
    { Icon: OndemandVideo, label: '影视' , key:'movie'},
    { Icon: Tv, label: '追剧' , key:'tv'},
    { Icon: PhoneAndroid, label: 'tiktok',key:'shortvideo' },
    { Icon: MusicNote, label: '歌曲',key:'music' },
    { Icon: Photo, label: '图片',key:'photo' },
  ])

  const { enqueueSnackbar } = useSnackbar();
  const navigate = useNavigate()


  useEffect(() => {
    getData()
    getUserInfo()
  },[])
  
  const getData = async () => {
    openPro(true)
    const res = await request.getSourceList()
    openPro(false)
    if (res.code === 200){

      let datalist = tabList.map(i => res.data[i.key] || [])
      
      datalist = datalist.map((item) => {
        let path = '/video'
        if (item.key === 'music') {
          path = '/music'
        } else if (item.key === 'photo') {
          path = '/photo'
        }
        if(item.key === 'music' && item.list) {
          let allList = item.list.reduce((pre,cur) => {
            pre.push(...cur.list)
            return pre
          },[])
          item.list.unshift({directory:'所有歌曲',list:allList})
        }
        return {path,...item}
      })

      setlist(datalist)
    } else {
      if(res.message){
        enqueueSnackbar(res.message, { variant: "warning" });
      }
    }
  }

  const getUserInfo = async () => {
    let token = localStorage.getItem('token')
    if(!token) return
    const res = await request.getUserInfo()
    if (res.code === 200){
      let userInfo = JSON.stringify(res.data)
      localStorage.setItem("userInfo", userInfo);
      props.updateUserInfo(res.data)
    } else {
      if(res.message){
        enqueueSnackbar(res.message, { variant: "warning" });
      }
    }
  }


  const handleChange = (event, newValue) => {
    // settabIdx(newValue);
    props.change(newValue)
  };


  const onchange = () => {
      changeTheme()
      console.log(theme);
  }

  const goRoute = (path,params) => {
    navigate(path,{
      replace:false,
      state:params
    })
  }

  const handleLoginOpen = () => {
    setregOpen(false)
    setloginOpen(true)
  }

  const handleLoginClose = () => {
    setloginOpen(false)
  }
  const handleRegOpen = () => {
    setloginOpen(false)
    setregOpen(true)
  }

  const handleRegClose = () => {
    setregOpen(false)
  }

  const openPro = (state) => {
    setproOpen(state)
  }


  const [anchorEl, setAnchorEl] = useState(null);
  const menuOpen = Boolean(anchorEl);
  const handleClickMenu = (event) => {
    setAnchorEl(event.currentTarget);
  };
  const handleCloseMenu = () => {
    setAnchorEl(null);
  };
  const handleQuit =() => {
    handleCloseMenu()
    localStorage.removeItem('userInfo')
    localStorage.removeItem('token')
    props.updateUserInfo(null)
  }

  const profileRef = useRef(null)

  const openAccountMenu = () => {
    profileRef.current.handleOpen()
    setAnchorEl(null);
  };

  

  return <>
    {/* 头部导航栏 */}
    <Box sx={{display:'flex',flexDirection:'column',height:'100%'}}>
      <Box sx={{ width: '100%', bgcolor: 'background.paper' }}>
        <Grid p={1.5} xs={12} md={12} sx={{display:'flex',alignItems:'flex-end',justifyContent:'center',fontSize:'15px'}}>
          <div>
            <img style={{width:'10%'}} src="/favicon/android-chrome-512x512_red.png" alt="" />
            <span style={{transform:'translate(-8px)'}}>&nbsp;&nbsp;电视+</span>
          </div>
          <Grid pr={2} sx={{position: 'absolute',right: '0'}} >
            {
              props.userInfo ?
              <Box sx={{ flexGrow: 1, overflow: 'hidden', px: 3 ,maxWidth:300,cursor:'pointer'}}>
                <Stack spacing={2} direction='row' alignItems='center' onClick={ handleClickMenu }>
                  <Avatar  alt={props.userInfo?.nickname}  src={import.meta.env.VITE_API_URL + '/' + props.userInfo?.headPic} />
                  {
                    !props.isMobile && <Typography noWrap>你好!&nbsp;&nbsp;{props.userInfo?.nickname}</Typography>
                  }
                  
                </Stack>
                <Menu
                  id="basic-menu"
                  anchorEl={anchorEl}
                  open={menuOpen}
                  onClose={handleCloseMenu}
                  MenuListProps={{
                    'aria-labelledby': 'basic-button',
                  }}
                >
                  <MenuItem>
                    <FormControlLabel
                      control={<MaterialUISwitch sx={{ m: 0 }} />}
                      label={props.isMobile ? "":"主题"}
                      onChange={onchange}
                      checked={theme.palette.mode === 'dark'}
                    />
                  </MenuItem>
                  <MenuItem onClick={openAccountMenu}>个人信息</MenuItem>
                  <MenuItem onClick={handleQuit}>退出</MenuItem>
                </Menu>
              </Box>
              :
              <Button variant="outlined" onClick={handleLoginOpen}>
                登录
              </Button>
            }
          </Grid>
        </Grid>
          <Grid xs={12} md={12} >
            <Tabs value={tabIdx} onChange={handleChange} centered  variant='fullWidth'>
              {
                tabList.map(({Icon,label},index) => <Tab icon={<Icon/>} key={index} label={label}  {...a11yProps(index)} />)
              }
            </Tabs>
          </Grid>
      </Box>
      {/* tabPanel 内容区域 */}
      <Box sx={{ bgcolor: 'background.paper',flex:'1',height:'100%' }} >
        <Container maxWidth="100%" sx={{ height:'100%'}}>
          <Box sx={{ width: '100%',height: '100%', bgcolor: 'action.hover',borderRadius:'20px' }}>
            <Grid container spacing={0} justifyContent='center' alignItems="center" sx={{ width: '100%',height: '100%' }}>
              <Box sx={{ position: 'relative',width: '98%',height: '98%', bgcolor: 'action.hover',borderRadius:'18px' }}>
                <img style={{position:'absolute',left:'5vw',top:'15vh',opacity:'0.8',width:'30%',zIndex:'0'}} src="/favicon/android-chrome-512x512.png" alt="" />
                {/* <Card/> */}
                {
                  list.map((item,index) =>
                      <CustomTabPanel  key={index} value={tabIdx} index={index} style={{height:'100%',overflowY:'auto'}} >
                        <CSSTransition in={index === tabIdx} timeout={500} classNames="animate">
                          <Stack spacing={{ xs: 1, sm: 2 }} direction="row" useFlexGap flexWrap="wrap">
                            {
                              item.list?.map((dir,index) => 
                                <Button key={index} sx={{fontSize: '1.3rem'}} color="success"  endIcon={<PlayCircle />} variant="contained" onClick={() => goRoute(item.path,{title:item.category,source:dir})} >{dir.directory}</Button>
                              )
                            }
                          </Stack>
                        </CSSTransition>
                      </CustomTabPanel>
                    )
                }
              </Box>
            </Grid>
          </Box>
        </Container>
      </Box>
    </Box>
    {/* 弹框:  登录框 注册框 个人信息弹框 loading动画 */}
    <Profile getUserInfo={getUserInfo}  profileRef={profileRef} userInfo={props.userInfo} avatarPic={import.meta.env.VITE_API_URL + '/' + props.userInfo?.headPic}/>
    <LoginView  {...{openPro}}  {...{handleRegOpen,handleClose:handleLoginClose,open:loginOpen}}></LoginView>
    <RegisterView {...{openPro}}   {...{handleLoginOpen,handleClose:handleRegClose,open:regOpen}}></RegisterView>
    {/* <Loading open={proOpen}/> */}
  </>
}





export default connect(mapStateToProps,mapDispatchToProps)(Home)
// export default Home